<template>
    <div class="map-container">
      <div class="map-controls">
        <button @click="connectWebSocket">连接WebSocket</button>
        <button @click="disconnectWebSocket">断开连接</button>
        <button @click="sendRequest">发送数据请求</button>
        <div class="status">连接状态: {{ connectionStatus }}</div>
      </div>
      <div ref="mapContainer" class="map"></div>
      <div class="vehicle-info" v-if="selectedVehicle">
        <h3>车辆详细信息</h3>
        <p><strong>车辆ID:</strong> {{ selectedVehicle.vehicleId }}</p>
        <p><strong>位置:</strong> {{ selectedVehicle.latitude.toFixed(6) }}, {{ selectedVehicle.longitude.toFixed(6) }}</p>
        <p><strong>速度:</strong> {{ selectedVehicle.speed.toFixed(1) }} km/h</p>
        <p><strong>方向:</strong> {{ selectedVehicle.heading.toFixed(1) }}°</p>
        <p><strong>最后更新:</strong> {{ formatTime(selectedVehicle.timestamp) }}</p>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, onBeforeUnmount } from 'vue'
  import L from 'leaflet'
  import 'leaflet/dist/leaflet.css'
  
  // 地图元素
  const mapContainer = ref(null)
  let map = null
  let socket = ref(null)
  
  // 状态管理
  const connectionStatus = ref('未连接')
  const vehicleData = ref({})
  const selectedVehicle = ref(null)
  const trailLayers = ref({})
  const markerLayers = ref({})
  
  // 默认多边形区域
  const defaultPolygon = [[116.5021289, 39.7484118],[116.5121289, 39.7484118],[116.5121289, 39.7584118],[116.5021289, 39.7584118],[116.5021289, 39.7484118]]
  
  // 初始化地图
  const initMap = () => {
    // 解决Leaflet图标问题
    delete L.Icon.Default.prototype._getIconUrl
    L.Icon.Default.mergeOptions({
      iconRetinaUrl: new URL('leaflet/dist/images/marker-icon-2x.png', import.meta.url).href,
      iconUrl: new URL('leaflet/dist/images/marker-icon.png', import.meta.url).href,
      shadowUrl: new URL('leaflet/dist/images/marker-shadow.png', import.meta.url).href
    })
  
    // 创建地图实例
    map = L.map(mapContainer.value).setView([39.7193029, 116.5036649], 18)
    
    // 添加地图图层
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map)
    
    // 绘制默认多边形区域
    L.polygon(defaultPolygon, {color: 'blue', fillOpacity: 0.1}).addTo(map)
  }
  
  // 连接WebSocket
  const connectWebSocket = () => {
    if (socket.value && socket.value.readyState === WebSocket.OPEN) {
      console.log('WebSocket已经连接')
      return
    }
  
    // 替换为你的WebSocket地址
    //const wsUrl = 'ws://localhost:8080/icv/perception'
    //const wsUrl = 'ws://192.168.200.52:8081/icv/perception'
    const wsUrl = 'ws://124.126.105.101:50000/icv/perception'
    socket.value = new WebSocket(wsUrl)
  
    socket.value.onopen = () => {
      connectionStatus.value = '已连接'
      console.log('WebSocket连接已建立')
    }
  
    socket.value.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data)
        if (data?.result?.length) {
          updateVehicleData(data.result)
        }
      } catch (e) {
        console.error('解析消息错误:', e)
      }
    }
  
    socket.value.onerror = (error) => {
      connectionStatus.value = '连接错误'
      console.error('WebSocket错误:', error)
    }
  
    socket.value.onclose = () => {
      connectionStatus.value = '已断开'
      console.log('WebSocket连接已关闭')
    }
  }
  
  // 断开WebSocket连接
  const disconnectWebSocket = () => {
    if (socket.value) {
      socket.value.close()
    }
  }
  
  // 发送请求消息给后端
  const sendRequest = () => {
    if (!socket.value || socket.value.readyState !== WebSocket.OPEN) {
      alert('请先建立WebSocket连接')
      return
    }
  
    const requestData = {
      action: "road_real_data_per",
      token: "TUSVN",
      data: JSON.stringify({
        type: 1,
        polygon: defaultPolygon,
        des: "twn2.0"
      })
    }
  
    socket.value.send(JSON.stringify(requestData))
    console.log('已发送请求:', requestData)
  }
  
  // 更新车辆数据
  const updateVehicleData = (vehicles) => {
    vehicles.forEach(vehicle => {
      const vehicleId = vehicle.vehicleId
      
      // 初始化车辆数据存储
      if (!vehicleData.value[vehicleId]) {
        vehicleData.value[vehicleId] = []
      }
      
      // 添加新数据点
      vehicleData.value[vehicleId].push(vehicle)
      
      // 只保留最近的30个点
      if (vehicleData.value[vehicleId].length > 30) {
        vehicleData.value[vehicleId].shift()
      }
      
      // 更新地图显示
      updateVehicleOnMap(vehicleId)
    })
  }
  
  // 更新地图上的车辆标记和轨迹
  const updateVehicleOnMap = (vehicleId) => {
    const points = vehicleData.value[vehicleId]
    if (!points.length) return
    
    const latestPoint = points[points.length - 1]
    const position = [latestPoint.latitude, latestPoint.longitude]
    
    // 创建或更新车辆标记
    if (!markerLayers.value[vehicleId]) {
      const icon = L.divIcon({
        className: 'vehicle-marker',
        html: `<div style="transform: rotate(${latestPoint.heading}deg)">🚗</div>`,
        iconSize: [24, 24]
      })
      
      markerLayers.value[vehicleId] = L.marker(position, { icon })
        .addTo(map)
        .bindPopup(`<b>车辆ID:</b> ${vehicleId}<br><b>速度:</b> ${latestPoint.speed.toFixed(1)} km/h`)
        .on('click', () => { selectedVehicle.value = latestPoint })
    } else {
      markerLayers.value[vehicleId]
        .setLatLng(position)
        .setPopupContent(`<b>车辆ID:</b> ${vehicleId}<br><b>速度:</b> ${latestPoint.speed.toFixed(1)} km/h`)
    }
    
    // 创建或更新轨迹线
    const trailPoints = points.map(p => [p.latitude, p.longitude])
    if (!trailLayers.value[vehicleId]) {
      trailLayers.value[vehicleId] = L.polyline(trailPoints, {
        color: getRandomColor(),
        weight: 3,
        opacity: 0.7
      }).addTo(map)
    } else {
      trailLayers.value[vehicleId].setLatLngs(trailPoints)
    }
  }
  
  // 辅助函数
  const getRandomColor = () => {
    return `hsl(${Math.random() * 360}, 70%, 50%)`
  }
  
  const formatTime = (timestamp) => {
    return new Date(timestamp).toLocaleTimeString()
  }
  
  // 生命周期钩子
  onMounted(() => {
    initMap()
    // 可以自动连接，也可以让用户手动点击连接
    // connectWebSocket()
  })
  
  onBeforeUnmount(() => {
    disconnectWebSocket()
    if (map) map.remove()
  })
  </script>
  
  <style scoped>
  .map-container {
    position: relative;
    height: 80vh;
    width: 100%;
    border: 1px solid #ccc;
    border-radius: 8px;
    overflow: hidden;
  }
  
  .map {
    height: 100%;
    width: 100%;
  }
  
  .map-controls {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 1000;
    display: flex;
    gap: 10px;
    background: white;
    padding: 8px;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.2);
  }
  
  .map-controls button {
    padding: 4px 8px;
    cursor: pointer;
  }
  
  .status {
    display: flex;
    align-items: center;
    padding: 0 8px;
  }
  
  .vehicle-info {
    position: absolute;
    bottom: 20px;
    right: 20px;
    z-index: 1000;
    background: white;
    padding: 12px;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.2);
    max-width: 300px;
  }
  
  .vehicle-info h3 {
    margin-top: 0;
    margin-bottom: 8px;
  }
  
  .vehicle-info p {
    margin: 6px 0;
  }
  </style>
  
  <style>
  .vehicle-marker {
    background: transparent;
    border: none;
  }
  </style>